package org.javaboy.idemponent.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.javaboy.idemponent.anno.Idemponent;
import org.javaboy.idemponent.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class IdemponentInterceptor implements HandlerInterceptor {
    @Autowired
    TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //这个实际上就是我们的接口方法
        HandlerMethod method = (HandlerMethod) handler;
        //获取接口方法上的注解
        Idemponent idemponent = method.getMethodAnnotation(Idemponent.class);
        if (idemponent == null) {
            //没有注解，直接放行（说明该方法不需要进行幂等性处理）
            return true;
        }
        boolean isPass = tokenService.checkToken(request);
        if (!isPass) {
            response.setContentType("text/plain;charset=utf-8");
            //校验失败，直接返回
            response.getWriter().write("幂等性校验失败");
        }
        return isPass;
    }
}
